/**********************************************************************\
 © COPYRIGHT 2006 Corporation for National Research Initiatives (CNRI);
                        All rights reserved.
               
        The HANDLE.NET software is made available subject to the
         Handle System Public License, which may be obtained at
         http://hdl.handle.net/4263537/5030 or hdl:4263537/5030
\**********************************************************************/

package net.handle.apps.servlet_proxy.handlers;

import net.handle.hdllib.*;
import net.handle.util.StringUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.handle.apps.servlet_proxy.*;

public class Url implements TypeHandler {

  /** 
  * Return true if the handle values contain a URL value or a value with
  * a sub-type of URL.
  */
  public boolean canRedirect(HandleValue values[]) {
    if(values==null) return false;
    for(int i=values.length-1; i>=0; i--) {
      if(values[i].hasType(Common.STD_TYPE_URL))
        return true;
    }
    return false;
  }
  
  
  /** 
  * Return true iff this TypeHandler can format the data from the given
  * HandleValue for a human client.
  */
  public boolean canFormat(HandleValue value) {
    return value!=null && value.hasType(Common.STD_TYPE_URL);
  }
  
  public String toHTML(String handle, HandleValue value){
    return "<a href=\""+value.getDataAsString()+"\">"+
      value.getDataAsString()+"</a>";
  }
  
  public boolean doRedirect(HttpServletRequest request, 
                            HttpServletResponse response, HttpParams params,
                            String handle, HandleValue values[])
    throws IOException
  {
    if(values==null) return false;
    
    String redirectURL = null;
    
    // first check for base URL values
    HandleValue val;
    byte valType[];
    for(int i=0; i<values.length; i++) {
      val = values[i];
      if(val==null) continue;
      valType = val.getType();
      if(valType==null) continue;
      if(Util.equalsCI(valType, Common.STD_TYPE_URL)) {
        redirectURL = val.getDataAsString();
        break;
      }
    }
    
    // if no simple URL value exists, look for URL sub-types
    if(redirectURL==null) {
      for(int i=0; i<values.length; i++) {
        val = values[i];
        if(val==null) continue;
        if(val.hasType(Common.STD_TYPE_URL)) {
          redirectURL = val.getDataAsString();
          break;
        }
      }
    }
    
    if(redirectURL==null) {
      // no value was found with type URL or any subtypes
      return false;
    }
    
    String urlSuffix = params.getParameter("urlappend");
    if (urlSuffix == null) urlSuffix = "";
    else urlSuffix = StringUtils.decodeURLIgnorePlus(urlSuffix);
    
    // send a redirect to the URL, with any suffix provided by the user
    try { 
      // don't use sendRedirect(), because it tries to be smart and 
      // occasionally mangles the uri(e.g. on mailto's)
      // response.sendRedirect(url+suffix); 
      response.setStatus(response.SC_MOVED_TEMPORARILY);
      response.setHeader("Location", redirectURL+urlSuffix);
      // print out terse page to avoid tomcat's redirect message for
      // things like mailto where a separate viewer is spawned
      // XXX: seems to be ignored by tomcat?
      OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
      out.write("\n<HTML><HEAD><TITLE>Handle Redirect</TITLE></HEAD>");
      out.write("\n<BODY><A HREF=\""+redirectURL+urlSuffix+"\">");
      out.write(redirectURL+urlSuffix+"</A></BODY></HTML>");
      out.close(); 
      return true;
    } catch (Exception e) {
      System.out.println("Error in Url.doRedirect for "+handle+": "+e); 
    }
    return false;
  }

  
  
}
